<template>
  <div class="supplier-check setting-content">
    <h2 class="setting-header">
      <strong>
        <span>公告管理</span>
      </strong>
    </h2>
    <div class="top-btns-box">
      <div class="top-btns">
        <el-button type="primary" style="margin: 10px 0" @click="handleOpenDialog(null,3)">新增公告</el-button>
      </div>
      <!-- <el-button type="primary" @click="toFront">前台访问</el-button> -->
    </div>
    <el-tabs v-model="queryData.state" class="demo-tabs" @tab-change="handleTabChange">
      <el-tab-pane :label="item.label" :name="item.value" v-for="(item, index) in stateOptions" :key="index"></el-tab-pane>
    </el-tabs>
    <SearchCmp style="margin: 10px 0;" v-if="searchCmpArray.length" :searchCmpArray="searchCmpArray" :searchForm="queryData" @onSubmit="handleSearch" />

    <div class="list-container">
      <RuifoxTable :loading="tableLoading" :default-index="true" :default-checkbox="true" v-model:tableData="tableData" v-model:fieldList="fieldList">
        <template #default-checkbox="{element}">
          <div class="table-div-check">
            <el-checkbox class="unmover" v-model="element.checked" @change="handleCheckTable(element.id)" size />
          </div>
        </template>
        <template #type="{element}">
          <span>{{typeOptions.find(item => item.value == element.type)?.label || '--'}}</span>
        </template>
        <template #state="{element}">
          <el-tag :type="getStateType(element.state)">{{getStateLabel(element.state)}}</el-tag>
        </template>
        <template #noticeTypeId="{element}">
          <span>{{getNoticeName(element.noticeTypeId)}}</span>
        </template>
        <template #options="{element}">
          <div class="table-td-option unmover">
            <el-button type="primary" link @click="handleOpenDialog(element.id, 1)">查看</el-button>
            <el-dropdown>
              <span class="el-dropdown-link unmover">
                <i class="iconfont">&#xe78d;</i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item v-if="element.state == 0" @click="handleOpenDialog(element.id, 2)">编辑</el-dropdown-item>
                  <el-dropdown-item v-if="element.state == 0" @click="handleChangeState(element.id, 1)">发布</el-dropdown-item>
                  <el-dropdown-item v-if="[1, 3].includes(element.state)" @click="handleAudit(element.id)">审核</el-dropdown-item>
                  <el-dropdown-item v-if="element.state == 2" @click="handleChangeState(element.id, 4)">撤稿</el-dropdown-item>
                  <el-dropdown-item v-if="element.state == 4" @click="handleChangeState(element.id, 2)">再次发布</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </RuifoxTable>
      <PaginationView
        :total="queryData.total"
        :pageSize="queryData.pageSize"
        :currentPage="queryData.currentPage"
        :allChoose="isAllChooseBtn"
        :pageChoose="isPageChooseBtn"
        :checkedNum="checkedNum"
        @changeSize="handleSizeChange"
        @currentChange="handleCurrentChange"
        @changePageChoose="handlePageChoose"
        @changeAllChoose="handleAllChoose"
        @invertChoose="handleInvertChoose"
        @refreshList="getTableData"
      />
    </div>

    <!-- 公告详情弹窗 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle" width="60%" :close-on-click-modal="false" :close-on-press-escape="false">
      <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="formData.title" placeholder="请输入标题" :readonly="dialogType === 1" />
        </el-form-item>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="阶段" prop="type">
              <el-select v-model="formData.type" placeholder="阶段" @change="handleChangeType" :readonly="dialogType === 1">
                <el-option v-for="item in typeOptions" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="项目类型" prop="type">
              <el-select v-model="formData.noticeTypeId" placeholder="请选择项目类型" @change="handleChangeType">
                <el-option v-for="item in noticeTypeList" :key="item.noticeTypeId" :label="item.value" :value="item.noticeTypeId" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="可关联项目" prop="projectId">
              <el-select v-model="formData.projectId" filterable placeholder="请选择项目">
                <el-option v-for="item in projectList" :key="item.id" :disabled="!item.canChoose" :label="item.name + (item.canChoose ? '（可关联）' : '')" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发布人" prop="author">
              <el-input v-model="formData.author" placeholder="请输入发布人" :readonly="dialogType === 1" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="内容" prop="content">
          <div :class="{ 'editor-disabled': dialogType === 1 }" style="width: 100%;">
            <RuifoxEditor style="width: 100%;" v-if="dialogVisible" v-model="formData.content" :readonly="dialogType === 1"></RuifoxEditor>
          </div>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.description" type="textarea" :rows="3" placeholder="请输入描述" :readonly="dialogType === 1" />
        </el-form-item>
        <el-form-item label="附件列表" prop="annex">
          <!-- 附件信息 -->
          <div class="file-box">
            <el-button type="primary" @click="handleShowFileUpload" :disabled="dialogType === 1">上传附件</el-button>
            <div class="file-list" v-if="formData?.annex?.length">
              <div class="file-item" v-for="(item, index) in formData.annex" :key="index">
                <div class="file-name" @click="handleFileDownLoad(item)">{{item.fileName}}</div>
                <div class="btns">
                  <el-button type="danger" link @click="hanldeDeletefile(item)" :disabled="dialogType === 1">删除</el-button>
                </div>
              </div>
            </div>
          </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button v-if="!formData.id" @click="handleSubmit(0)">暂存</el-button>
          <el-button type="primary" @click="handleSubmit(1)" v-if="dialogType !== 1">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <FilesUpload v-if="showFilesUpload" v-model:showDialog="showFilesUpload" :isPublic="true" @getFileList="insertFiles" :isToJpg="true"></FilesUpload>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import {
  selectPage,
  selectById,
  insertNotice,
  updateNotice,
  selectNoticeType,
  selectListByNoticeType,
  updateNoticeState,
} from '@/api/notice'
import { tableList as mixTable } from '@ruifox-cms/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import RuifoxEditor from '@/views/bidding/components/RuifoxEditor.vue'
import { FilesUpload } from '@ruifox-cms/components'
import { useRouter } from 'vue-router'

const router = useRouter()
const {
  queryData,
  tableData,
  tableLoading,
  checkedNum,
  isAllChooseBtn,
  isPageChooseBtn,
  getTableData,
  handleSearch,
  handleCurrentChange,
  handleSizeChange,
  handlePageChoose,
  handleAllChoose,
  handleInvertChoose,
  handleCheckTable,
} = mixTable({
  getListApi: selectPage,
  batchFuncTip: '是否确定删除选中项？',
})

onMounted(() => {
  handleSearch()
})

const toFront = () => {
  router.push({ path: '/bidding/user/noticeList' })
}
const defaultQueryData = {
  keyWords: '',
  state: -1, //-1 全部 0 暂存 1 待审核 2 已发布 3 未通过 4 已发布 5 已撤稿
}
Object.assign(queryData, structuredClone(defaultQueryData))

const typeOptions = ref([
  { label: '报名开始', value: 1 },
  { label: '报名结束', value: 2 },
  { label: '定标通知', value: 3 },
])

const fieldList = ref([
  {
    title: '标题',
    name: 'title',
  },
  {
    title: '阶段',
    name: 'type',
  },
  {
    title: '项目类型',
    name: 'noticeTypeId',
  },
  {
    title: '发布人',
    name: 'author',
  },
  {
    title: '发布时间',
    name: 'publishTime',
  },
  {
    title: '状态',
    name: 'state',
  },
  {
    title: '操作',
    width: 180,
    fixed: 'right',
    name: 'options',
  },
])

const searchCmpArray = ref([
  { label: '关键词', key: 'keyWords' },
  { label: '类型', key: 'type', form_type: 'select', options: typeOptions.value },
])

// 弹窗相关
const dialogVisible = ref(false)
const dialogType = ref(1) // 1查看 2编辑 3新增
const dialogTitle = ref('')
const formRef = ref(null)
const defaultFormData = {
  title: null,
  type: 1,
  author: null,
  description: null,
  content: null,
  projectId: null,
  thumb: null,
  annex: [],
  state: 0, //
}
const stateOptions = ref([
  {
    label: '全部',
    value: -1,
  },
  {
    label: '暂存',
    value: 0,
  },
  {
    label: '待审核',
    value: 1,
  },
  {
    label: '已发布',
    value: 2,
  },
  {
    label: '未通过',
    value: 3,
  },
  {
    label: '已撤稿',
    value: 4,
  },
])

const noticeTypeList = ref([])
const selectNoticeTypeAsync = async () => {
  const res = await selectNoticeType()
  if (res.code === 20000) {
    noticeTypeList.value = res.data
  }
}
selectNoticeTypeAsync()

const getNoticeName = (id) => {
  return noticeTypeList.value.find((item) => item.noticeTypeId == id).value || '-'
}

const handleTabChange = () => {
  setTimeout(() => {
    handleSearch()
  }, 0)
}
const formData = ref(structuredClone(defaultFormData))

const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  type: [{ required: true, message: '请选择类型', trigger: 'change' }],
  author: [{ required: true, message: '请输入发布人', trigger: 'blur' }],
  // description: [{ required: true, message: '请输入描述', trigger: 'blur' }],
  content: [{ required: true, message: '请输入内容', trigger: 'blur' }],
}
const handleChangeType = async () => {
  return new Promise((resolve, reject) => {
    selectListByNoticeType({ type: formData.value.type }).then((res) => {
      if (res.code === 20000) {
        projectList.value = res.data
        resolve()
      } else {
        reject()
      }
    })
  })
}

const projectList = ref([])
const handleOpenDialog = async (id, type) => {
  dialogType.value = type
  dialogTitle.value = type === 1 ? '查看公告' : type === 2 ? '编辑公告' : '新增公告'
  dialogVisible.value = true
  if (id) {
    const res = await selectById({ id })
    if (res.code === 20000) {
      formData.value = res.data
    }
  } else {
    formData.value = structuredClone(defaultFormData)
  }
  await handleChangeType()
}

const handleSubmit = async (state) => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      let res
      if (formData.value.id) {
        res = await updateNotice(formData.value)
      } else {
        formData.value.state = state
        res = await insertNotice(formData.value)
      }
      if (res.code === 20000) {
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        dialogVisible.value = false
        handleSearch()
      }
    }
  })
}

const handleChangeState = (id, state) => {
  ElMessageBox.confirm('是否确认执行操作？', '操作确认', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
  }).then(async () => {
    let res = await updateNoticeState({ id, state })
    if (res.code === 20000) {
      ElMessage({
        message: '操作成功',
        type: 'success',
      })
      handleSearch()
    }
  })
}
const handleAudit = (id) => {
  ElMessageBox.confirm('请选择通过或不通过', '审核确认', {
    distinguishCancelAndClose: true,
    confirmButtonText: '通过',
    cancelButtonText: '不通过',
    type: 'warning',
  })
    .then(async () => {
      let res = await updateNoticeState({ id, state: 2 })
      if (res.code === 20000) {
        ElMessage({
          message: '操作成功',
          type: 'success',
        })
        handleSearch()
      }
    })
    .catch(async (action) => {
      if (action === 'cancel') {
        let res = await updateNoticeState({ id, state: 3 })
        if (res.code === 20000) {
          ElMessage({
            message: '操作成功',
            type: 'success',
          })
          handleSearch()
        }
      }
    })
}

// 附件信息
const showFilesUpload = ref(false)
const handleShowFileUpload = () => {
  showFilesUpload.value = true
}
const insertFiles = (files) => {
  if (formData.value.annex == null) formData.value.annex = []
  files.forEach((item) => {
    formData.value.annex.push({
      fileName: item.name,
      fileUrl: item.url,
    })
  })
}

const getStateType = (state) => {
  const typeMap = {
    0: 'info', // 暂存
    1: 'warning', // 待审核
    2: 'success', // 已发布
    3: 'danger', // 未通过
    4: 'info', // 已撤稿
  }
  return typeMap[state] || 'info'
}

const getStateLabel = (state) => {
  const labelMap = {
    0: '暂存',
    1: '待审核',
    2: '已发布',
    3: '未通过',
    4: '已撤稿',
  }
  return labelMap[state] || '未知'
}

const hanldeDeletefile = (val) => {
  formData.value.annex = formData.value.annex.filter((item) => item.fileName != val.fileName)
}
// 下载
const handleFileDownLoad = (item) => {
  window.open(item.fileUrl, '_blank')
  // download(item.fileUrl, item.fileName)
}
</script>

<style lang="scss" scoped>
.setting-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.top-btns-box{
  width: 100%;
  display: flex;
  justify-content: space-between;
}
.top-btns {
  display: flex;
  align-items: flex-start;
  gap: 0 10px;
}

.ruifox-table tbody tr {
  cursor: auto;
  td {
    p {
      @include textEllipsis(16px, 1);
    }
    a {
      color: $mainColor;
      @include textEllipsis(16px, 1);
      &:hover {
        text-decoration: underline;
      }
    }
  }
}

.avatar-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
  }
  :deep(.el-upload:hover) {
    border-color: var(--el-color-primary);
  }
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  line-height: 178px;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
::v-deep .editor-header {
  display: none;
}
.site-ico-box {
  display: flex;
  align-items: center;
  gap: 0 10px;
  .site-ico {
    width: 178px;
    height: 178px;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
.file-box {
  .file-list {
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    gap: 5px 0;
    .file-item {
      width: 600px;
      display: flex;
      justify-content: flex-start;
      align-items: center;
      gap: 0 10px;
      .file-name {
        max-width: 400px;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        font-size: 12px;
        color: #333;
        cursor: pointer;
        &:hover {
          text-decoration: underline;
          color: $mainColor;
        }
      }
    }
  }
}
.editor-disabled {
  position: relative;
  left: 0;
  top: 0;
  opacity: 0.5;
  width: 100%;
  height: 100%;
  background: #000;
  z-index: 998;
  pointer-events: none;
}
</style>
